//
//  PDFJSViewController.m
//  PDFJSReader
//
//  Created by limeng on 2018/7/25.
//  Copyright © 2018年 lilu. All rights reserved.
//

#import "PDFJSWKViewController.h"
#import "PDFWebView.h"

@interface PDFJSWKViewController () <WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, UIGestureRecognizerDelegate>
{
    NSInteger _pageNumber;
}

/**
 是否加载成功
 */
@property (nonatomic, assign) BOOL loadSuccess;
@property (nonatomic, strong) PDFWebView *webView;

/**
 计时
 */
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger readTime;

@end

@implementation PDFJSWKViewController

- (void)dealloc{
    NSLog(@"%s", __func__);
}

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
        
    [self.view addSubview:self.webView];
    [self.webView loadPDFFile:self.filePath];
    
    //双击
    UITapGestureRecognizer *doubleTap = ({
        UITapGestureRecognizer *tapGestureRecognizer =
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapped:)];
        tapGestureRecognizer.numberOfTapsRequired = 2;
        tapGestureRecognizer.delegate = self;
        tapGestureRecognizer;
    });
    
    [self.view addGestureRecognizer:doubleTap];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //注册方法监听
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"webViewPageChanging"];
    
    if (self.loadSuccess && !_timer) {
        //加载成功才可以计时
        [self startTimer];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"webViewPageChanging"];
    [self endTimer];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.webView.frame = self.view.bounds;
    
    if (self.navigationController &&
        (!self.navigationController.navigationBar.isHidden) &&
        self.navigationController.navigationBar.translucent) {
            //导航栏半透明
            CGFloat statusH = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
            CGFloat navH = CGRectGetHeight(self.navigationController.navigationBar.frame);
            CGFloat topHeight = statusH + navH;
            CGFloat webH = CGRectGetHeight(self.view.bounds) - topHeight;
            self.webView.frame = CGRectMake(0, topHeight, CGRectGetWidth(self.view.bounds), webH);
            return;
    }
}

#pragma mark - lazy
- (PDFWebView *)webView{
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [[WKUserContentController alloc]init];
        configuration.allowsInlineMediaPlayback = YES;
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        configuration.preferences = preferences;
        
        // !!!: ---------- iOS9以后才有这个属性,设置后才能跨域 ----------
        [preferences setValue:@(YES) forKey:@"allowFileAccessFromFileURLs"];
        
        PDFWebView *webView = [[PDFWebView alloc] initWithFrame:self.view.frame configuration:configuration];
        
        webView.startPageNumber = self.startPage;

        webView.backgroundColor = [UIColor whiteColor];
        webView.navigationDelegate = self;
        webView.UIDelegate = self;
        
        _webView = webView;
    }
    return _webView;
}

- (void)setStartPage:(NSInteger)startPage{
    _startPage = startPage;
    _pageNumber = startPage;
}

/**
 更新最大阅读的页码
 */
- (void)updateMaxReadPageNumber:(NSInteger)page{
    _pageNumber = page;
    if (page > self.maxReadPageNumber) {
        self.maxReadPageNumber = page;
    }
    NSLog(@"当前:%zd, 最大:%zd", page, self.maxReadPageNumber);
}

#pragma mark - method
// !!!: ---------- 计时部分 ----------
- (void)startTimer{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
}

- (void)endTimer{
    [_timer invalidate];
    _timer = nil;
    
    //结束计时时回调
    NSDictionary *dict = @{@"maxReadPage" : @(self.maxReadPageNumber),
                           @"currentPage" : @(self.pageNumber),
                           @"time" : @(self.readTime)
                           };
    self.readEndHandler(dict);
    
}

- (void)updateTime{
    self.readTime ++;
}

#pragma mark - GestureRecognizer
- (void)doubleTapped:(UITapGestureRecognizer *)recognizer{
    NSLog(@"双击!!!!!!!!!");
    dispatch_async(dispatch_get_main_queue(), ^{
        //        NSString *string = @"window.PDFViewerApplication.zoomIn()";
        NSString *string = @"document.getElementById('zoomIn').click();";
        [self.webView evaluateJavaScript:string completionHandler:nil];
    });
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"webViewPageChanging"]) {
        NSLog(@"webViewPageChanging");
        NSInteger page = [message.body integerValue];
        [self updateMaxReadPageNumber:page];
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    self.loadSuccess = YES;
    [self startTimer];
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
